package com.ldzhao.blog.util;

import org.apache.commons.lang3.tuple.Pair;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * <ClassName>LocalCache</ClassName>
 * <Description>本地缓存</Description>
 *
 * @Author liuxianzhao
 * @Date 2018年10月04日 11:08
 */
public class LocalCache {
    private static final ConcurrentMap<String, Object> cache = new ConcurrentHashMap<>();
    private static final ConcurrentMap<String, Pair<Long, Integer>> expireTimer = new ConcurrentHashMap<>();

    public static Object get(String key) {
        return get(key, 12 * 60 * 60 * 1000, key_ -> null);
    }

    public static Object get(String key, int expire, CacheFunction cacheFunction) {
        Pair<Long, Integer> timeStamp = expireTimer.get(key);
        Object result = cache.get(key);
        if (result != null && (timeStamp == null || (timeStamp != null && System.currentTimeMillis() - timeStamp.getKey() < timeStamp.getValue()))) {
            return result;
        } else {
            result = cacheFunction.fetchData(key);
            if (result != null) {
                expireTimer.put(key, Pair.of(System.currentTimeMillis(), expire));
                cache.put(key, result);
            }
        }
        return result;
    }

    @FunctionalInterface
    public interface CacheFunction {
        Object fetchData(String key);
    }
}
